<?php

class AttachmentController extends AdminController {    
    
	private $separator = '{$$$}';
	public $disableScripts = array();
	
    public function actionIndex() {
        $model = new Attachment('search');
        $model->unsetAttributes();  // clear any default values
        if (isset($_GET['Attachment']))
            $model->attributes = $_GET['Attachment'];
        $this->render('index', array(
          'model' => $model,
        ));
	
    }
    
    function actions() {
        return array(
          'update' => array(
            'class' => 'lib.components.actions.UpdateAction',
            'modelClass' => 'Attachment',
            'messages' => array('success' => t('MSG_INFO_UPDATE_SUCCESS', 'messages', array('{0}' => t('LBL_ATTACHMENT', 'attachment'))))
          ),
          'delete' => array(
            'class' => 'lib.components.actions.DeleteAction',            
            'ajaxView' => "//share/_delete",
          	'customAction' => "deleteAttachment",
            'messages' => array('success' => t('MSG_INFO_DELETE_SUCCESS', 'messages' , array('{0}' => t('LBL_ATTACHMENT', 'attachment'))))
          ),
          'error' => array(
            'class' => 'lib.components.actions.ErrorAction',
          ),
        );
    }
	
    public function actionGetAllOperation(){
        
        $allcontrollers = Attachment::model()->getAllController();
        $actions = array();
        foreach ($allcontrollers as $key => $controller) {
             $class = $controller."Controller";
                
                $hascombine =  method_exists ( $class , 'actions' );
                array_push($actions,$controller.'.'.'*');
                if($hascombine == 1){
                    $combinedActions = call_user_func(array($class, 'actions'));
                    foreach ($combinedActions as $key => $value){
                        array_push($actions,$controller.".".ucfirst($key));
                    }
                }

                $allmethods =get_class_methods($class);
                foreach ($allmethods as $key => $value){
                    if(strlen(strstr($value,'action'))>0){
                        if($value != 'actions'){
                            $value = str_replace('action', '', $value);
                            array_push($actions,$controller.".".ucfirst($value));
                        }
                    }
                }
        }
        echo CJSON::encode($actions);
    }
    
    public function loadModel() {
        $model = null;
        if (isset($_GET['id']))
        {
            $ids = explode(',', $_GET['id']);
            if (isset($ids)) {
                $criteria = new CDbCriteria;
                $criteria->addInCondition('id', $ids);
                $model = Attachment::model()->findAll($criteria);
            }         
        }
        return $model;
        
    }
    
    public function renderMessage($status, $content) {
    	echo $status . $this->separator . $content;
    	Yii::app()->end();
    }
    
    public function stopJS() {
    	$defaultDisableScripts = array(
    			'jquery.js',
    			'jquery.min.js',
    			'jquery-ui.min.js'
    	);
    
    	// Merge with user set scripts which should be disabled
    	if (is_array($this->disableScripts)) {
    		$this->disableScripts = CMap::mergeArray(
    				$defaultDisableScripts, $this->disableScripts);
    	}
    	else
    		throw new CException(t('MSG_DISABLE_SCRIPT', 'messages'));
    
    	// Disable scripts
    	foreach ($this->disableScripts as $script)
    		Yii::app()->clientScript->scriptMap[$script] = false;
    }
    
    public function actionCreateAttachment() {
    	$this->stopJS ();
    	$model = new Attachment('create');
    	if (method_exists($model, 'unsetAttributes')) {
    		$model->unsetAttributes();
    	}
    	$model->profile_id = $_GET['profile_id'];
    	if (isset ( $_POST ['Attachment'] )) {
    
    		$model->attributes = $_POST ['Attachment'];
    		$fileUpload = $_FILES ['Attachment'];
    		$oldAttachment = $model->file_name;
    
    		if ($fileUpload ['size'] ['file_name'] > 0) {
    			$newName = gmdate ( 'YmdGis' ) . '_' . stringSafeFile ( $fileUpload ['name'] ['file_name'] );
    			$model->file_name = $newName;
    		}
    
    		// Save only if model validates
    		if ($model->validate ()) {
    			if ($fileUpload ['size'] ['file_name'] > 0) {
    				if ($model->save ()) {
    					move_uploaded_file ( $fileUpload ['tmp_name'] ['file_name'], ATTACHMENT_FOLDER . $newName );
    					$this->renderMessage('success', t('MSG_INFO_CREATE_SUCCESS', 'messages', array('{0}' => t('LBL_ATTACHMENT', 'attachment'))));
    				}
    			}
    		} else {
    			$model->file_name = $oldAttachment;
    		}
    	}
    	$this->renderMessage('render', $this->renderPartial('_formAttachment', array('model' => $model), true, true));
    }
    
    public function deleteAttachment(){
    	$model = null;
    	$isDelete = null;
    	if (isset($_GET['id'])) {
    		$ids = explode(',', $_GET['id']);
    		if (isset($ids)) {
    			$criteria = new CDbCriteria;
    			$criteria->addInCondition('id', $ids);
    			$model = Attachment::model()->findAll($criteria);
    		}
    	}
    
    	//Must throw CHttpException, If not, when ajax request, error will not run errorHandler
    	if ($model == NULL || count($model) == 0) {
    		//Must return 200 to client recieve this error
    		throw new CHttpException(200, t('THERE_WAS_AN_ERROR_WHILE_DELETING._PLEASE_TRY_AGAIN.', 'messages'));
    	}
    	foreach($model as $i => $item){
    		$file_name = $item->file_name;
    		$isDelete = $item->delete();
    		if($isDelete && file_exists(ATTACHMENT_FOLDER . $item->file_name)){
    			unlink(ATTACHMENT_FOLDER . $file_name);
    		}
    	}
    	if($isDelete){
    		echo CJSON::encode(array(
    				'status' => 'success',
    				'content' => t('MSG_INFO_DELETE_SUCCESS', 'messages' , array('{0}' => t('LBL_ATTACHMENT', 'attachment'))),
    		));
    		// Stop script execution
    		Yii::app()->end();
    	}else{
    		echo CJSON::encode(array(
    				'status' => 'error',
    				'content' =>  t('MSG_INFO_DELETE_UNSUCCESS', 'messages' , array('{0}' => t('LBL_ATTACHMENT', 'attachment'))),
    		));
    		// Stop script execution
    		Yii::app()->end();
    	}
    }
}

?>